﻿using System;
namespace Jumbot.API.Discuz
{
    public class AccessDbCom : SqlServerDbCom
    {
        public override bool Login(string username, string password, int expDays, bool inVisible, string reFerer)
        {
            string Sql;
            if (password.Length == 32)//表示密文
                Sql = String.Format("select top 1 [tpp],[ppp],[pmsound],[invisible],[sigstatus],[uid] from [{2}users] where [username]='{0}' and [password]='{1}'", username, password, Command.RC.Tableprefix);
            else
                Sql = String.Format("select top 1 [tpp],[ppp],[pmsound],[invisible],[sigstatus],[uid] from [{2}users] where [username]='{0}' and [password]='{1}'", username, Command.Md5(password), Command.RC.Tableprefix);

            System.Data.DataTable myDt = Command.DBC.vDataTable(Sql);
            if (Object.Equals(myDt, null) || myDt.Rows.Count <= 0)
            {
                Command.Register(username, 0, string.Empty, password, string.Empty);
                myDt = Command.DBC.vDataTable(Sql);
            }
            GetUserInfo userinfo = new GetUserInfo(myDt);
            if (Object.Equals(myDt, null) || myDt.Rows.Count <= 0) return false;

            Command.DBC.vExecuteNonQuery(String.Format("UPDATE [{0}users] SET [lastvisit]=Now(), [lastip]='{2}' WHERE [username]='{1}'", Command.RC.Tableprefix, username, Command.RC.UserIP));

            return Command.WriteLoginCookie(userinfo, inVisible, reFerer, expDays, password);

        }

        public override void LoginOut()
        {
            try
            {
                System.Web.HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies["dnt"];
                if (Object.Equals(cookie, null))
                {
                    cookie = new System.Web.HttpCookie("dnt");
                }
                else
                {
                    if (!Object.Equals(cookie.Values["userid"], null))
                    {
                        string Uid = cookie.Values["userid"].ToString();
                        if (!String.IsNullOrEmpty(Uid))
                        {
                            int uid;
                            Int32.TryParse(Uid, out uid);
                            Command.DBC.vExecuteNonQuery(String.Format("UPDATE [{0}users] SET [oltime] = [oltime] + DATEDIFF(n,[lastvisit],Now()) WHERE [uid]={1};delete from [{0}online] where [userid]={1};", Command.RC.Tableprefix, uid));
                        }
                    }
                }
                cookie.Values.Clear();
                cookie.Expires = DateTime.Now.AddYears(-1);
                if (Command.IsValidDomain(Command.RC.doMain))
                {
                    cookie.Domain = Command.RC.doMain;
                }
                System.Web.HttpContext.Current.Response.AppendCookie(cookie);
            }
            catch
            { }
        }
    }
}
